package com.cq.hd.system.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.system.excel.dto.HfRegionsExcelDto;
import com.cq.hd.system.po.TbHfRegionsPo;
import com.cq.hd.system.service.TbHfRegionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class HfRegionsListener extends AnalysisEventListener<HfRegionsExcelDto> {

    private final TbHfRegionsService hfRegionsService;

    public HfRegionsListener(TbHfRegionsService hfRegionsService) {
        this.hfRegionsService = hfRegionsService;
    }

    @Override
    public void invoke(HfRegionsExcelDto hfRegionsExcelDto, AnalysisContext analysisContext) {
        save(hfRegionsExcelDto);
    }

    private void save(HfRegionsExcelDto hfRegionsExcelDto) {
        List<TbHfRegionsPo> list = hfRegionsService.list(new QueryWrapper<TbHfRegionsPo>()
                .eq("region_grade", 3)
                .eq("local_name", hfRegionsExcelDto.getAreaName()));
        if (!CollectionUtils.isEmpty(list)) {
            return;
        }

        List<TbHfRegionsPo> provinces = hfRegionsService.list(new QueryWrapper<TbHfRegionsPo>()
                .eq("region_grade", 1)
                .eq("local_name", hfRegionsExcelDto.getProvinceName()));
        if (CollectionUtils.isEmpty(provinces)) {
            log.error("未找到省份数据");
            return;
        }

        TbHfRegionsPo tbProvinceHfRegionsPo = provinces.get(0);

        List<TbHfRegionsPo> citys = hfRegionsService.list(new QueryWrapper<TbHfRegionsPo>()
                .eq("parent_id", tbProvinceHfRegionsPo.getId())
                .eq("region_grade", 2)
                .eq("local_name", hfRegionsExcelDto.getCityName()));
        if (CollectionUtils.isEmpty(citys)) {
            log.error("未找到省份数据");
            return;
        }

        TbHfRegionsPo tbCityHfRegionsPo = citys.get(0);

        TbHfRegionsPo tbHfRegionsPo = new TbHfRegionsPo();
        tbHfRegionsPo.setParentId(tbCityHfRegionsPo.getId());
        tbHfRegionsPo.setRegionGrade(3);
        tbHfRegionsPo.setLocalName(hfRegionsExcelDto.getAreaName());
        tbHfRegionsPo.setCode(hfRegionsExcelDto.getAreaCode());
        hfRegionsService.save(tbHfRegionsPo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


}
